package it.polito.let.jhp.types;

import it.polito.let.jhp.SemanticException;

import java.io.Serializable;
import java.util.Map;
import java.util.TreeMap;

public class EnumType extends ComplexType implements JHPType, Serializable {

	private static final long serialVersionUID = 6641273349056296813L;

	private final static TypeCode type = TypeCode.ENUM;

	private JHPType type1;

	private JHPType type2;

	private RenderType render;

	private Map<Object,Object> enumValues;

	public EnumType(JHPType t1, JHPType t2) throws SemanticException {
		super(new BaseType(type));
		type1 = t1;
		type2 = t2;
		render = RenderType.select;
		enumValues = new TreeMap<Object,Object>();
	}

	@Override
	public boolean typeCheck(Object o, TypeCode t) {
		return type1.typeCheck(o,t) && enumValues.containsKey(o);
	}


	public boolean typeCheck(Object o1,TypeCode t1 ,Object o2,TypeCode t2) {
		return type1.typeCheck(o1,t1) && type2.typeCheck(o2,t2) ;
	}

	public void addAttribute(TypeAttr a, Value[] v) throws SemanticException {
		try {
			switch (a) {
			case enumerate:
				setEnumerate(v[0].getVal(), v[0].getType(), v[1].getVal(), v[1].getType());
				break;

			case render:
				if (!v[0].getType().equals(TypeCode.RENDER))
					throw new SemanticException("Wrong render attribute");
				render = (RenderType) v[0].getVal();
				break;

			default:
				throw new SemanticException("Attribute "+a.name()+" can't be set on an Enumerative");
			}

		} catch (NullPointerException e) {
			throw new SemanticException("Enumerative type mismatch");
		}
	}

	private void setEnumerate(Object o1,TypeCode t1 ,Object o2,TypeCode t2) throws SemanticException { 
		Object ob;

		ob=enumValues.put(o1, o2);
		if(ob!=null)
			throw new SemanticException("Duplicated key value");
	}

	public RenderType getRender() {
		return render;
	}

	public Map<Object,Object> getEnumValues () {
		return enumValues;
	}

	@Override
	public String clientSideCheck(String value) {
		return type1.clientSideCheck(value);
	}

	@Override
	public String toString() {
		StringBuffer res = new StringBuffer("One of the followings:\r\n");
		for (Object n : enumValues.keySet())
		{
			res.append("\t"+n.toString()+ " --> "+ enumValues.get(n)+"\r\n");	
		}
		return res.toString();
	}
}
